// pages/admin/admin.js
import {
  formatDate,
  base64
} from "../../utils/util.js"
import {
  url
} from "../../api/congfig"

import {
  // 查询商品
  getGoods,
  // 查询推荐商品
  recommend,
  // 删除商品
  delGoods,
  // 查询订单
  getExchange,
  // 订单发货
  exchange,
  // 新增商品
  addRecommend,
  // 获取个人信息
  getAbout,
  // 上下架商品
  uploadGoods,
  // 移除推荐
  deleteRecommend,
  
  // 查询商品
  shopIndex,
  shopIndexRecommend,
} from '../../api/index'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 积分选择区间
    integral1: '',
    integral2: '',
    // 搜索条件
    activeTab: 0,

    // 激活图标 
    active: 0,
    // 图标
    iconArr: [{
        index: 0,
        normal: '/static/image/shangTab.png',
        active: '/static/image/shangTabSelect.png',
      },
      {
        index: 1,
        normal: '/static/image/ding.png',
        active: '/static/image/dingSelect.png',
      },
      {
        index: 2,
        normal: '/static/image/wode.png',
        active: '/static/image/wode1.png',
      },
    ],
    // 用户信息
    userInfo: {},
    // 商品数据 推荐
    recommendArr: [],
    // 时间选择器
    currentDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }

      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    // 打开时间选择器
    startTimeBob: false,
    // 开始时间
    startTime: formatDate(new Date().getTime()),
    // 结束时间
    endTimeBob: false,
    // 开始时间
    endTime: formatDate(new Date().getTime()),

    // 搜索内容
    searchValue: '',
    // 发货弹窗提示
    modelBob: false,
    // 删除商品弹窗提示
    modelBobDel: false,
    // 商品列表数据
    goodsArr: [],
    recommendArr: [],
    // 删除商品id
    comId: '',
    // 商品列表下拉刷新
    refresherBob: false,
    comStatus: '',

    // 订单数据
    ORDarr: [],
    // 兑换订单id
    ordId: '',
    // 兑换订单类型
    status: ''
  },
  onShow() {
    console.log('show');
    this.onTabChange()
    this.getAboutPage()
  },
  // 获取用户信息
  async getAboutPage() {
    try {
      const dataObj = await getAbout()
      console.log("获取个人信息", dataObj.data);
      if (dataObj.code == 200) {
        const obj = dataObj.data
        console.log(obj);
        this.setData({
          userInfo: obj
        })
      }
    } catch (error) {
      console.log("获取个人信息：", error);
    }
  },
  // 开始商品下拉
  refresherStart() {
    console.log("下拉开始");
    this.setData({
      refresherBob: true
    })

    setTimeout(() => {
      this.setData({
        refresherBob: false
      })
    }, 1000);

  },

  // 商品下拉完成
  refresherEnd() {
    console.log("商品下拉完成");
    this.getShopGoods()
  },
  // 获取商品信息
  async getShopGoods() {
    const {
      integral1,
      integral2,
      searchValue,
      activeTab
    } = this.data
    console.log("传递的参数是", searchValue);
    // const cartObj = await getCart()
    // console.log("购物车：", cartObj);
    if (activeTab == '0') {
      const dataObj = await shopIndex({
        page_num: 1,
        page_size: 10000,
        start_price: integral1,
        end_price: integral2,
        name: searchValue
      })
      console.log("订单查询结果：", dataObj);
      if (dataObj.code == 200) {
        // dataObj.data.forEach(item => {
        //   item.create_time = formatDate(item.create_time)
        // })
        // if (cartObj.code == 200) {
        //   dataObj.data.data_list.forEach(item => {
        //     let obj = cartObj.data.find(items => items.goods_id == item.id)
        //     item.cartNum = obj ? obj.goods_count : 0
        //   })
        // }
        this.setData({
          goodsArr: dataObj.data.data_list
        })
      }
    } else {
      const dataObj = await shopIndexRecommend({
        page_num: 1,
        page_size: 10000,
        start_price: integral1,
        end_price: integral2,
        name: searchValue,
        type: activeTab
      })
      console.log("订单查询结果：", dataObj);
      if (dataObj.code == 200) {
        // dataObj.data.forEach(item => {
        //   item.create_time = formatDate(item.create_time)
        // })
        // if (cartObj.code == 200) {
        //   dataObj.data.forEach(item => {
        //     let obj = cartObj.data.find(items => items.goods_id == item.goods.id)
        //     item.goods.cartNum = obj ? obj.goods_count : 0
        //   })
        // }
        this.setData({
          recommendArr: dataObj.data
        })
      }
    }
  },
  // 顶部标签切换
  onChangeTab(e) {
    console.log(e.detail);
    this.setData({
      activeTab: e.detail.index
    })
    this.getShopGoods();
  },
  // 跳转详情页
  onDumpPage(e) {
    const obj = e.currentTarget.dataset.obj
    console.log("商品数据:", obj);
    wx.navigateTo({
      url: '/pages/admin/productDetails/productDetails?obj=' + JSON.stringify(obj),
    })
  },
  // 确认移除推荐开启
  async delConfirm3(e) {
    try {
      const id = e.currentTarget.dataset.id
      const dataObj = await deleteRecommend({
        id
      })
      console.log("移除推荐",dataObj);
      if(dataObj.code==200){
        this.getShopGoods()
      }
    } catch (error) {
      console.log("移除推荐失败：", error);
    }
  },
//   // 获取商品列表
//   async getShopGoods(name = '') {
//     try {
//       const dataObj = await getGoods({
//         name
//       })
//       console.log("商品列表：", dataObj);
//       this.setData({
//         goodsArr: dataObj.data
//       })
//     } catch (error) {
//       console.log("获取商品列表失败", error);
//     }
//   },
  // 修改头像
  changeImg() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success(res) {
        try {
          console.log(res.tempFiles[0].tempFilePath)
          const token = wx.getStorageSync('token')
          console.log(token);
          wx.uploadFile({
            url: url + '/home/update/avatar', // 仅为示例，非真实的接口地址
            filePath: res.tempFiles[0].tempFilePath,
            name: 'file',
            header: {
              token
            },
            formData: {},
            complete(res) {
              console.log("返回参数", res);
              if (res.statusCode == 200) {
                const dataCode = JSON.parse(res.data).code
                console.log(JSON.parse(res.data));
                if (dataCode == 200) {
                  that.getAboutPage()
                }
              }
            },
          });
        } catch (error) {
          console.log("更换头像错误：", error);
        }
      }
    })
  },


  // 查询订单列表
  async getExchangePage() {
    try {
      const {
        startTime,
        endTime
      } = this.data
      const dataObj = await getExchange({
        start_time: startTime + " 00:00:00",
        end_time: endTime + " 23:59:59"
      })
      console.log("订单查询结果：", dataObj);
      if (dataObj.code == 200) {
        dataObj.data.forEach(item => {
          item.create_time = formatDate(item.create_time)
        })
        this.setData({
          ORDarr: dataObj.data
        })
      }
    } catch (error) {
      console.log("获取订单失败");
    }

  },

  // 确认发货弹窗开启
  async ORDconfirm2(e) {
    console.log({
      modelBob: true,
      status: e.currentTarget.dataset.type,
      ordId: e.currentTarget.dataset.id
    });
    this.setData({
      modelBob: true,
      status: e.currentTarget.dataset.type,
      ordId: e.currentTarget.dataset.id
    })
  },
  ORDclose() {
    this.setData({
      modelBob: false
    })
  },
  // 确认发货
  async ORDconfirm() {
    try {
      const ordId = this.data.ordId
      const status = this.data.status
      console.log("兑换参数", {
        id: ordId,
        status
      });
      const dataObj = await exchange({
        id: ordId,
        status
      })
      console.log("兑换结果：", dataObj);
      if (dataObj.code == 200) {
        this.getExchangePage()
        if (status == '1') {
          wx.showToast({
            icon: 'none',
            title: "已发货"
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: "已拒绝"
          })
        }

      } else {
        console.log("订单兑换错误");
      }

      this.setData({
        modelBob: false
      })

    } catch (error) {
      console.log("确认发货失败");
    }
  },
  // 确认上架下架弹窗开启
  delConfirm2(e) {
    console.log(e.currentTarget.dataset.id);
    this.setData({
      modelBobDel: true,
      comId: e.currentTarget.dataset.id,
      comStatus: e.currentTarget.dataset.status
    })
  },
  delClose() {
    this.setData({
      modelBobDel: false
    })
  },
  // 确认删除
  async delConfirm() {
    const id = this.data.comId
    const status = this.data.comStatus
    try {
      let dataObj = {}
      if (status == '0') {
        console.log("上架");
        dataObj = await uploadGoods({
          id,
          status: '1'
        })
      } else {
        console.log("下架");
        dataObj = await uploadGoods({
          id,
          status: '0'
        })
      }
      console.log("上架下架商品：", dataObj);
      this.getShopGoods()
    } catch (error) {
      console.log("上架下架商品失败：", error);
    }

    this.setData({
      modelBobDel: false
    })
  },
  // 确认搜索
  async onClickSearch() {
    console.log(this.data.searchValue);
    const name = this.data.searchValue
    this.getShopGoods(name)
  },

  // 时间选择器
  onInput(event) {
    console.log("选择时间：", event.detail);
    this.setData({
      currentDate: event.detail,
    });
  },
  // 打开时间选择器
  timeBob() {
    console.log('1212');
    this.setData({
      startTimeBob: true,
    })
  },
  // 确认选择开始时间
  timeConfirm(e) {
    console.log(e.detail);
    const date = formatDate(e.detail)
    console.log(date);
    this.setData({
      startTime: date,
      startTimeBob: false,
      endTimeBob: true
    })
  },
  // 确认结束时间
  timeConfirmEnd(e) {
    console.log(e.detail);
    const date = formatDate(e.detail)
    const that = this
    const startTime = new Date(that.data.startTime).getTime()
    if (e.detail >= startTime) {
      this.setData({
        endTime: date,
        endTimeBob: false
      })
      // 查询订单
      this.getExchangePage()
    } else {
      wx.showToast({
        icon: 'none',
        title: '结束时间必须大于开始时间',
      })
    }
  },
  // 关闭开始
  closeStartTime() {
    this.setData({
      startTimeBob: false,
    })
  },
  // 关闭结束
  closeEndTime() {
    this.setData({
      startTimeBob: true,
      endTimeBob: false
    })
  },

  // tab栏切换
  onTabChange(event) {
    if (event) {
      this.setData({
        active: event.detail
      });
    }

    switch (this.data.active) {
      case 0:
        console.log("商品");
        this.getShopGoods()
        break;
      case 1:
        this.getExchangePage()
        console.log("订单");
        break;
      case 2:
        this.getRecommend()
        console.log("个人中心");
        break;
      default:
        console.log("不存在");
        break;
    }

  },
  // 新增推荐商品
  async addRecommendConfirm2(e) {
    try {
      const goods_id = e.currentTarget.dataset.id
      const type = e.currentTarget.dataset.type
      console.log("推荐商品id:", goods_id);
      const dataObj = await addRecommend({
        goods_id,
        order: 0,
        type
      })
      console.log("新增推荐：", dataObj);
      this.getShopGoods();
    } catch (error) {
      console.log("新增推荐商品：", error);
    }
  },
  // 获取推荐商品
  async getRecommend() {
    try {
      const dataObj = await recommend()
      console.log("获取推荐商品:", dataObj.data);
      if (dataObj.code == 200) {
        this.setData({
          recommendArr: dataObj.data
        })
      } else {
        console.log("获取推荐商品错误");
      }
    } catch (error) {
      console.log("获取推荐商品错误", error);
    }
  },

  // 退出登录
  showPopup() {
    this.setData({
      userInfo: {},
    });
    wx.removeStorageSync('userInfo')

    wx.reLaunch({
      url: '/pages/login/login'
    })
  },

  // 提示
  toast(e) {
    console.log(e.currentTarget.dataset.text);
    wx.showToast({
      icon: 'none',
      title: e.currentTarget.dataset.text,
    })
  },

  // 移除推荐
  async delRecommend(e) {
    try {
      const id = e.currentTarget.dataset.id
      const dataObj = await deleteRecommend({
        id
      })
      console.log("移除推荐",dataObj);
      if(dataObj.code==200){
        this.getRecommend()
      }
    } catch (error) {
      console.log("移除推荐失败：", error);
    }
  },

  // 前往商品发布页
  toCommodity() {
    wx.navigateTo({
      url: '/pages/admin/adminCommodity/adminCommodity?released=0',
    })
  },

  // 前往订单详情页
  toORDPage(e) {
    console.log("订单详情：", e.currentTarget.dataset.item);
    const obj = e.currentTarget.dataset.item
    wx.setStorageSync('ordData', JSON.stringify(obj))
    wx.navigateTo({
      url: '/pages/admin/adminORD/adminORD',
    })
  },
  // 前往修改个人信息页
  toUpdateUser(e) {
    wx.navigateTo({
      url: '/pages/my/updateUser/updateUser?type=' + e.currentTarget.dataset.type,
    })
  },

  // 前往商城通知页
  toNotive() {
    wx.navigateTo({
      url: '/pages/admin/adminMy/notice/notice',
    })
  },

  // 前往优惠卷页
  toCoupon() {
    wx.navigateTo({
      url: '/pages/admin/adminMy/coupon/coupon',
    })
  },

  // 前往积分赠送页
  toBonusPoints() {
    wx.navigateTo({
      url: '/pages/admin/adminMy/bonusPoints/bonusPoints',
    })
  },
  // 前往用户管理
  toUsers() {
    wx.navigateTo({
      url: '/pages/admin/users/users',
    })
  }

})